// 导入文件模块
import archiver from "archiver";
import * as fs from "fs";
// // 导入文件压缩模块
// // const archiver = require("archiver");
// // import { archiver } from "archiver";
// import pkg from "archiver";
import path from "path";
// const { archiver } = pkg;
const __dirname = path.resolve();

const zero = (time) => {
  if (time < 10) {
    return "0" + time;
  } else {
    return time;
  }
};

const AddFile = function (list, path) {
  list.forEach(function (el) {
    let file = fs.lstatSync(path + el);
    if (file.isDirectory()) {
      let files = fs.readdirSync(path + el);
      let Path = path + el + "/";
      archive.directory(Path, el);
    } else {
      archive.file(path + el, { name: el });
    }
  });
};

let name = JSON.parse(fs.readFileSync("./package.json")).name;
let fileName =
  name +
  "-" +
  new Date().getFullYear() +
  "-" +
  zero(new Date().getMonth() + 1) +
  "-" +
  zero(new Date().getDate()) +
  "-" +
  zero(new Date().getHours()) +
  "-" +
  zero(new Date().getMinutes()) +
  ".zip";

let output = fs.createWriteStream(__dirname + "/" + "dist.zip");

let archive = archiver("zip");
output.on("end", function () {
  console.log("Data has been drained");
});

output.on("error", function (err) {
  console.log("压缩失败");
  throw err;
});

output.on("close", function () {
  console.log("压缩成功");
});

archive.pipe(output);
const files = fs.readdirSync(__dirname + "/dist");
const patha = __dirname + "/dist/";
// archive.file(__dirname + '/dist/index.html', {name: 'index.html'});
AddFile(files, patha);
// archive.directory(__dirname + '/dist/static/', 'static');
archive.finalize();
